package ServerOutput;

import Server.Server;
import Users.Stats;
import Users.UserOutputManager;
import java.io.*;
import java.sql.SQLException;

public class OutputManager {
    private String root;
    private Stats statsObj;
    
    public OutputManager() throws Exception {
        this("");
    }
    
    public OutputManager(String rootPath) throws Exception {
        root = rootPath;
        statsObj = new Stats();
    }
    
	public Output getOutput(String requestedPath) throws Exception {
		Output out;

		if (UserOutputManager.isUserPage(requestedPath)) {
			statsObj.pageRequested(requestedPath);
			return UserOutputManager.getUserOutput(requestedPath);
		}

		try {
			//Bandom sukonstruot dataInputStreama is failo. 
			DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(new File(root + requestedPath))));

			out = new Output(true);
			out.setDataDataInputStream(dis);
			out.setReturnCode(Server.ReturnCodes.OK_200);

			if(requestedPath.endsWith(".htm") || requestedPath.endsWith(".html") || requestedPath.endsWith(".txt")) {
				out.setOutputType(Server.FileTypes.textHtml);
			} else if (requestedPath.endsWith(".jpeg") || requestedPath.endsWith(".jpg") || requestedPath.endsWith(".JPG") || requestedPath.endsWith(".JPEG")) {
				out.setOutputType(Server.FileTypes.imageJpeg);
			} else if (requestedPath.endsWith(".gif") || requestedPath.endsWith(".GIF")) {
				out.setOutputType(Server.FileTypes.imageGif);
			} else {
				out.setOutputType(Server.FileTypes.none);
			}

			statsObj.pageRequested(requestedPath);

		} catch (FileNotFoundException ex) {
			out = new Output(false);
			out.setOutputType(Server.FileTypes.none);
			out.setReturnCode(Server.ReturnCodes.NOT_FOUND_404);
		}

		return out;
	}
}
